﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;
using KenLib.BusinessObject;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.ComponentModel;
using System.IO;

public partial class JOINT_frmJ_TraineeListSelectCheck : System.Web.UI.Page
{
    面接情報Manager _面接情報Manager = new 面接情報Manager();
    面接詳細情報Manager _面接詳細情報Manager = new 面接詳細情報Manager();
    本社情報Manager _本社情報Manager = new 本社情報Manager();
    /// <summary>
    /// Coder: Thanh Dong
    /// Event: Page load
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        ((JOINT_MstPage_JOINT)this.Master).HideLiArea("frmJ_TraineeListSelectCheck");
        ((JOINT_MstPage_JOINT)this.Master).changeTitle("候補者確定一覧");
        if (Session["frmJ_TraineeListSelect"] == null)
        {
            Response.Redirect("frmJ_TraineeListSelect.aspx");
        }
        lbl_CongTy.Text = Session["frmJ_TraineeSearch_ddl_組合員企業選択_Text"].ToString() + " ";
        if (!IsPostBack)
        {
            
            if (CheckData() == false)
            {
                string strHeader = "No,登録年月日,氏名,性別,年齢,身長,体重,視力,最終学歴,在学状態,就業経験有無,経験作業名1,経験作業名2,経験作業名3,具体的仕事内容,日本語学習経験,現住所,出身地";
                ShowGridViewNotClassEmpty(grv, strHeader, "データがありません。");
            }
            else
            {
                DataTable dt = ConvertDataTableToDataTable();
                grv.DataSource = dt;
                grv.DataBind();
            }

        }
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Convert List to Datatable
    /// </summary>
    /// <returns></returns>
    public DataTable ConvertDataTableToDataTable()
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["frmJ_TraineeListSelect"];
        return dt;
    }
    
    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Check datatable is null
    /// </summary>
    /// <returns></returns>
    public bool CheckData()
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["frmJ_TraineeListSelect"];
        if (dt.Rows.Count == 0)
        {
            return false;
        }
        return true;
        
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Export file csv
    /// </summary>
    /// <param name="dt"></param>
    public void ExportCSV(DataTable dt)
    {
        #region //xls
        //Response.Clear();
        //Response.Buffer = true;
        //Response.AddHeader("content-disposition","attachment;filename=GridViewExport.csv");
        //Response.Charset = "";
        //Response.ContentType = "application/vnd.ms-excel";
        //System.IO.StringWriter sw = new System.IO.StringWriter();
        //HtmlTextWriter hw = new HtmlTextWriter(sw);
        //grv.AllowPaging = false;
        //grv.DataSource = dt;
        //grv.DataBind();
        ////Change the Header Row back to white color
        //grv.HeaderRow.Style.Add("background-color", "#FFFFFF");
        ////Apply style to Individual Cells
        //grv.HeaderRow.Cells[0].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[1].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[2].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[3].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[4].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[5].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[6].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[7].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[8].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[9].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[10].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[11].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[12].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[13].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[14].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[15].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[16].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[17].Style.Add("background-color", "green");
        //grv.HeaderRow.Cells[18].Style.Add("background-color", "green");
        //for (int i = 0; i < grv.Rows.Count; i++)
        //{
        //    GridViewRow row = grv.Rows[i];
        //    //Change Color back to white
        //    row.BackColor = System.Drawing.Color.White;

        //    //Apply text style to each Row
        //    row.Attributes.Add("class", "textmode");

        //    //Apply style to Individual Cells of Alternating Row
        //    if (i % 2 != 0)
        //    {
        //        row.Cells[0].Style.Add("background-color", "#C2D69B");
        //        row.Cells[1].Style.Add("background-color", "#C2D69B");
        //        row.Cells[2].Style.Add("background-color", "#C2D69B");
        //        row.Cells[3].Style.Add("background-color", "#C2D69B");
        //        row.Cells[4].Style.Add("background-color", "#C2D69B");
        //        row.Cells[5].Style.Add("background-color", "#C2D69B");
        //        row.Cells[6].Style.Add("background-color", "#C2D69B");
        //        row.Cells[7].Style.Add("background-color", "#C2D69B");
        //        row.Cells[8].Style.Add("background-color", "#C2D69B");
        //        row.Cells[9].Style.Add("background-color", "#C2D69B");
        //        row.Cells[10].Style.Add("background-color", "#C2D69B");
        //        row.Cells[11].Style.Add("background-color", "#C2D69B");
        //        row.Cells[12].Style.Add("background-color", "#C2D69B");
        //        row.Cells[13].Style.Add("background-color", "#C2D69B");
        //        row.Cells[14].Style.Add("background-color", "#C2D69B");
        //        row.Cells[15].Style.Add("background-color", "#C2D69B");
        //        row.Cells[16].Style.Add("background-color", "#C2D69B");
        //        row.Cells[17].Style.Add("background-color", "#C2D69B");
        //        row.Cells[18].Style.Add("background-color", "#C2D69B");
        //    }
        //}
        //grv.RenderControl(hw);
        //Response.Output.Write(sw.ToString());
        //Response.Flush();
        //Response.End(); 
        #endregion


        string stOutput = "";
        string sHeaders = "";
        for (int i = 0; i < dt.Columns.Count-2; i++)
        {
            sHeaders = sHeaders.ToString() + Convert.ToString(dt.Columns[i]) + ", ";
        }
        stOutput += sHeaders + "\r\n";
        // Export data.  

        foreach (DataRow dr in dt.Rows)
        {
            string stLine = "";
            for (int i = 0; i < dt.Columns.Count-2; i++)
            {
                stLine = stLine.ToString() + Convert.ToString(dr[i]).Replace(",", " -") + ",";
            }
            stOutput += stLine + "\r\n";
        }
        stOutput = stOutput.Replace("/", " l ");
        string path = Server.MapPath("../CSV/");
        
        string str_組合選択 = "";
        string str_組合員企業選択 = "";
        DataTable dt_組合選択 = frmJ_TraineeListSelectCheck_Select企業名英語_本社情報(Convert.ToInt32(Session["frmJ_TraineeSearch_ddl_組合選択"]));
        if (dt_組合選択.Rows.Count > 0)
        {
            str_組合選択 = dt_組合選択.Rows[0]["企業名英語"].ToString();
        }
        DataTable dt_組合員企業選択 = frmJ_TraineeListSelectCheck_Select企業名英語_本社情報(Convert.ToInt32(Session["frmJ_TraineeSearch_ddl_組合員企業選択"]));
        if (dt_組合員企業選択.Rows.Count > 0)
        {
            str_組合員企業選択 = dt_組合員企業選択.Rows[0]["企業名英語"].ToString();
        }
        string filename = str_組合選択 + str_組合員企業選択 + string.Format("{0:yyyyMMdd}", DateTime.Now) + ".csv";
        //bool temp = FileInUse(filename);
        //if (temp == false)
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('filenameが開いているので新規CSVファイルを作成できません');</script>");
        //    return;
        //}
        //else
        //{
        System.IO.FileStream fs = new System.IO.FileStream(path + filename, System.IO.FileMode.Create);
        StreamWriter bw = new StreamWriter(fs, System.Text.Encoding.UTF8);
        bw.Write(stOutput);
        bw.Flush();
        bw.Close();
        fs.Close();
        ClientScript.RegisterStartupScript(this.GetType(), "dw", "<script>window.open('" + Request.Url.AbsoluteUri.Replace("JOINT/frmJ_TraineeListSelectCheck.aspx", "CSV/") + filename + "');</script>", false);
        //} 
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Check exists path
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    //public bool FileInUse(string path)
    //{
    //    try
    //    {
    //        //Just opening the file as open/create
    //        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
    //        {
    //            //If required we can check for read/write by using fs.CanRead or fs.CanWrite
    //        }
    //        return true;
    //    }
    //    catch (IOException ex)
    //    {
    //        return false;
    //    }
    //}
  

    /// <summary>
    /// Coder: Thanh Dong
    /// Event: Export file csv
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCSV出力_Click(object sender, EventArgs e)
    {
        DataTable dt = ConvertDataTableToDataTable();
        if (Session["frmJ_TraineeSearch_ddl_組合選択"].ToString() != "" && Session["frmJ_TraineeSearch_ddl_組合選択"] != null && Session["frmJ_TraineeSearch_ddl_組合員企業選択"] != null && Session["frmJ_TraineeSearch_ddl_組合員企業選択"].ToString() != "")
        {
            ExportCSV(dt);
        }
        else
        {
            Response.Redirect("frmJ_TraineeListSelect.aspx");
        }
        
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Event: Export file pdf
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnPDF出力_Click(object sender, EventArgs e)
    {
        DataTable dt = ConvertDataTableToDataTable();
        if (Session["frmJ_TraineeSearch_ddl_組合選択"].ToString() != "" && Session["frmJ_TraineeSearch_ddl_組合選択"] != null && Session["frmJ_TraineeSearch_ddl_組合員企業選択"] != null && Session["frmJ_TraineeSearch_ddl_組合員企業選択"].ToString() != "")
        {
            ExportPdfTable(dt);
        }
        else
        {
            Response.Redirect("frmJ_TraineeListSelect.aspx");
        }
        
    }
    
    /// <summary>
    /// Coder: Thanh Dong
    /// Event: Paging
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv.PageIndex = e.NewPageIndex;
        DataTable dt = ConvertDataTableToDataTable();
        grv.DataSource = dt;
        grv.DataBind();
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Show gridview empty
    /// </summary>
    /// <param name="grv"></param>
    /// <param name="strTableHeader"></param>
    /// <param name="strEmpty"></param>
    public void ShowGridViewNotClassEmpty(GridView grv, string strTableHeader, string strEmpty)
    {
        DataTable dt = new DataTable();
        string[] arrColumnNames = strTableHeader.Split(',');
        foreach (string str in arrColumnNames)
        {
            dt.Columns.Add(str);
        }
        grv.ShowFooter = false;
        DataRow r = dt.NewRow();
        dt.Rows.InsertAt(r, 0);
        grv.DataSource = dt;
        grv.DataBind();
        grv.Rows[0].Cells.Clear();
        TableCell cell = new TableCell();
        cell.ColumnSpan = grv.Columns.Count + 1;
        cell.Text = strEmpty;
        grv.Rows[0].Cells.Add(cell);

    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Cut string if string long then 20 character
    /// </summary>
    /// <param name="temp"></param>
    /// <returns></returns>
    public string ShowTextLength(string temp)
    {
        if (temp.Length > 20)
        {
            temp = temp.Substring(0, 20) + "...";
        }
        return temp;
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Cut string if string long then 30 character
    /// </summary>
    /// <param name="temp"></param>
    /// <returns></returns>
    public string ShowTextLength1(string temp)
    {
        if (temp.Length > 30)
        {
            temp = temp.Substring(0, 30) + "...";
        }
        return temp;
    }

    
    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Export file pdf
    /// </summary>
    /// <param name="PdfFileName"></param>
    /// <param name="dt"></param>
    /// <returns></returns>
    public void ExportPdfTable(DataTable dt)
    {
        int cols = dt.Columns.Count-2;
        int rows = dt.Rows.Count;
        Document doc = new Document(PageSize.A4, 2f, 4f, 2f, 4f); //iTextSharp document
        doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
        PdfPTable t = new PdfPTable(cols);
        BaseFont bf = BaseFont.CreateFont("c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font f1 = new iTextSharp.text.Font(bf, 15, Font.NORMAL);
        Font f2 = new iTextSharp.text.Font(bf, 5, Font.NORMAL);
        t.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        var columnwidth = new[] { 1f, 3f, 3f, 1.5f, 1f, 1f, 1f, 1.5f, 2f, 2f, 1.6f, 4f, 4f, 4f, 3f, 3f, 5f, 3f };
        //cell object
        PdfPCell c,c1;
        //create new font based on BaseFont
        Font fontContent = new Font(bf, 7);
        Font fontHeader = new Font(bf, 9);
        PdfWriter.GetInstance(doc, Page.Response.OutputStream);
        t.WidthPercentage = 100;
        t.SetWidths(columnwidth);
        doc.Open();
        Chunk title = new Chunk("候補者確定一覧 \n\n", f1);
        Paragraph p = new Paragraph();
        //write header
        PdfPTable t2 = new PdfPTable(cols);
        for (int j = cols - 1; j >= 0; j--)
        {
            t2.SetWidths(columnwidth);
            t2.WidthPercentage = 100;
            Phrase pr = new Phrase((dt.Columns[j].Caption != null &&
              dt.Columns[j].Caption.Length > 0) ? dt.Columns[j].Caption :
              dt.Columns[j].ColumnName, fontHeader);

            c1 = new PdfPCell(pr);
            c1.BackgroundColor = new BaseColor(169, 169, 169);
            c1.HorizontalAlignment = Element.ALIGN_CENTER;
            t2.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            t2.AddCell(c1);
        }
        //write table content
        for (int i = 1; i < rows+1; i++)
        {
            for (int j = cols - 1; j >= 0; j--)
            {
                string temp = dt.Rows[i - 1][j].ToString();
                temp = temp.Replace("(", " ");
                temp = temp.Replace(")", " ");
                temp = temp.Replace(".", "");
                c = new PdfPCell(new Phrase(temp, fontContent));
                if (i % 2 != 0)
                {
                    c.BackgroundColor = new BaseColor(255, 228, 196);//169-169-169
                }
                else
                {
                    c.BackgroundColor = BaseColor.WHITE;
                }
                c.HorizontalAlignment = Element.ALIGN_RIGHT;
                t.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                t.AddCell(c);
            }

            if (i % 20 == 0)
            {
                PdfPTable t1 = new PdfPTable(cols);
                for (int j1 = cols - 1; j1 >= 0; j1--)
                {
                    t1.SetWidths(columnwidth);
                    t1.WidthPercentage = 100;
                    Phrase pr = new Phrase((dt.Columns[j1].Caption != null &&
                      dt.Columns[j1].Caption.Length > 0) ? dt.Columns[j1].Caption :
                      dt.Columns[j1].ColumnName, fontHeader);
                    c1 = new PdfPCell(pr);
                    c1.BackgroundColor = new BaseColor(169, 169, 169);
                    c1.HorizontalAlignment = Element.ALIGN_CENTER;
                    t1.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                    t1.AddCell(c1);
                }
                doc.NewPage();
                p.Alignment = Element.ALIGN_CENTER;
                p.Add(title);
                doc.Add(p);
                doc.Add(t1);
                doc.Add(t);
                p = new Paragraph();
                t = new PdfPTable(cols);
                t.SetWidths(columnwidth);
                t.WidthPercentage = 100;
            }
           
        }


        doc.NewPage();
        p.Alignment = Element.ALIGN_CENTER;
        p.Add(title);
        doc.Add(p);
        doc.Add(t2);
        doc.Add(t);
        doc.Close();
        Page.Response.ContentType = "application/pdf";
        string str_組合選択 = "";
        string str_組合員企業選択 = "";
        DataTable dt_組合選択 = frmJ_TraineeListSelectCheck_Select企業名英語_本社情報(Convert.ToInt32(Session["frmJ_TraineeSearch_ddl_組合選択"]));
        if (dt_組合選択.Rows.Count > 0)
        {
            str_組合選択 = dt_組合選択.Rows[0]["企業名英語"].ToString();
        }
        DataTable dt_組合員企業選択 = frmJ_TraineeListSelectCheck_Select企業名英語_本社情報(Convert.ToInt32(Session["frmJ_TraineeSearch_ddl_組合員企業選択"]));
        if (dt_組合員企業選択.Rows.Count > 0)
        {
            str_組合員企業選択 = dt_組合員企業選択.Rows[0]["企業名英語"].ToString();
        }
        string filename = str_組合選択 + str_組合員企業選択 + string.Format("{0:yyyyMMdd-hhmm}", DateTime.Now) + ".pdf";
        Page.Response.AddHeader("content-disposition", "attachment;filename=" + filename + "");
        Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Page.Response.Write(doc);
        Page.Response.End();
    }

    /// <summary>
    /// Coder: Thanh Dong
    /// Function: Insert data in table 面接情報 and 面接詳細情報
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn確定_Click(object sender, EventArgs e)
    {
        //Kiem tra session null
        if (Session["frmJ_TraineeSearch_ddl_組合選択"] == null || Session["frmJ_TraineeSearch_ddl_組合員企業選択"] == null || Session["frmJ_TraineeSearch_txt_面接日"] == null)
        {
            Response.Redirect("frmJ_TraineeSearch.aspx");
        }
        else
        {
            Response.Redirect("frmJ_CandidateSendEmail.aspx");
        }
    }

    public DataTable frmJ_TraineeListSelectCheck_Select企業名英語_本社情報(int 企業ID)
    {
        return _本社情報Manager.frmJ_TraineeListSelectCheck_Select企業名英語_本社情報(企業ID);
    }
}



